<?php

namespace App\Http\Controllers\Admin\Admins;

use Illuminate\Http\Request;
use App\Http\Controllers\BaseController;
use Jenson\BaseAdmin\Libraries\Helper as MBHelper;
use Jenson\BaseAdmin\Models\Admin;

class AdminsController extends BaseController
{
    /**
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     *
     * 管理员列表
     */
    public function index(Request $request){
        $condition = $request->get('condition','name');
        if($request->isMethod('post')){
            # 要执行的代码
            $query = Admin::query()->latest();
            $keywords = $request->get('keywords',null);
            if($condition == 'username') { # 管理员昵称
                if ($keywords) {
                    $query->where('username', 'like', '%' . $keywords . '%');
                }
            }else if($condition == 'email') { # 邮箱
                if ($keywords) {
                    $query->where('email', 'like', '%' . $keywords . '%');
                }
            }else if($condition == 'fullname') { # 真实姓名
                if ($keywords) {
                    $query->where('fullname', 'like', '%' . $keywords . '%');
                }
            }
            $pageSize = $request->get('limit',10);
            # 计算offset值
            $offset = $request->get('offset',0);
            # 总数
            $total = $query->count();
            $data = $query->limit($pageSize)->offset($offset)->get();
            if($data){
                foreach($data as $key=>$val){
                    if($val['roles'] == 'is_super_user'){
                        $data[$key]['roles'] = '超管';
                    }else{
                        $data[$key]['roles'] = '普通';
                    }
                }
            }
            $data->toArray();
            ret([
                'total'=>$total,
                'data'=>$data
            ]);
        }
        $subtitle = '管理员管理';
        $nav = 'admin';
        return view('admin.admins.index',compact('subtitle','nav'));

    }
    /**
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\View\View
     * @throws \Exception
     *
     * Add
     */
    public function add(Request $request){
        if($request->isMethod('post')){
            $validator = \Validator::make($request->all(),[
                'username' => 'required',
                'password' => 'required',
                'fullName' => 'required',
                'email' => 'required|email',
                'status' => 'numeric',
            ], [
                'username.required' => '用户名不能为空',
                'password.required' => '密码不能为空',
                'fullName.required' => '姓名不能为空',
                'email.required' => '邮箱不能为空',
                'email.email' => '邮箱格式不正确',
                'status.numeric' => '状态字段异常',
            ]);
            if ($validator->fails()) {
                return redirect()->back()->withErrors($validator)->withInput($request->all());
            }
            # 判断用户名或邮箱是否存在
            $adminCount = Admin::query()->where('username',$request->username)
                ->orWhere('email', $request->email)
                ->count();
            if ($adminCount > 0){
                return redirect()->back()->withErrors("用户名或邮箱已存在，不可重复添加!")->withInput($request->all());
            }
            $create['username'] = $request->username;
            $create['password'] = bcrypt($request->password);
            $create['fullName'] = $request->fullName;
            $create['email'] = $request->email;
            $create['status'] = $request->status;
            \DB::beginTransaction();
            try{
                Admin::query()->create($create);
                # 记录管理员操作日志
                $params = [
                    'admin_id' => session('uid'),
                    'operation' => config('admin_operate.add_admin'),
                    'ip' => $_SERVER['REMOTE_ADDR'],
                ];
                MBHelper::addAdminLog($params);
                \DB::commit();
                return redirect()->back()->withErrors("is_save_success")->withInput();
            }Catch(\Exception $exception){
                \DB::rollBack();
                return redirect()->back()->withErrors($exception->getMessage())->withInput();
            }
        }
        $subtitle = '添加管理员';
//        $roles = array();
//        $getName = $request->get('roles_name',null);
        $compact = compact('subtitle');
        return view('admin.admins.add',$compact);
    }

    /**
     * @param Request $request
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\View\View
     * @throws \Exception
     *
     * 管理员编辑
     */
    public function edit(Request $request,$id){
        $url = route('admin.index');
        $success = 'success';
        $params = [
            'url'=>$url,
            'success'=>$success
        ];
        $data = Admin::query()->find($id);
        $subtitle = '编辑管理员';
        $errorMsg = false;
        if($data['roles'] == 'is_super_user'){
            $errorMsg = true;
        }
        if($request->isMethod('post')){
            $validator = \Validator::make($request->all(),[
                'username' => 'required',
                'fullName' => 'required',
                'email' => 'required|email',
                'status' => 'numeric',
            ], [
                'username.required' => '用户名不能为空',
                'fullName.required' => '姓名不能为空',
                'email.required' => '邮箱不能为空',
                'email.email' => '邮箱格式不正确',
                'status.numeric' => '状态字段异常',
            ]);
            if ($validator->fails()) {
                return redirect()->back()->withErrors($validator)->withInput($request->all());
            }
            $password = $request->get('password');
            if($password){
                $update['password'] = bcrypt($password);
            }
            $update['username'] = $request->get('username');
            $update['fullName'] = $request->get('fullName');
            $update['email'] = $request->get('email');
            $update['status'] = $request->get('status');
            \DB::beginTransaction();
            try{
                Admin::query()->where('id',$id)->update($update);
                # 记录管理员操作日志
                if(config('mbcore_baseadmin.baseadmin_admin_log_add')) {
                    $params = [
                        'admin_id' => session('uid'),
                        'operation' => config('admin_operate.edit_admin'),
                        'ip' => $_SERVER['REMOTE_ADDR'],
                    ];
                    MBHelper::addAdminLog($params);
                }
                \DB::commit();
                return redirect()->back()->withErrors("success")->withInput();
            }Catch(\Exception $e){
                \DB::rollBack();
                return redirect()->back()->withErrors($e->getMessage())->withInput();
            }
        }
        $compact = compact('data','subtitle','params','errorMsg');
        return view('admin.admins.edit',$compact);
    }

    /**
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     *
     * 管理员操作日志
     */
    public function log(){
        $url = route('admin.log.list');
        return redirect($url);
    }
}
